# -*- coding: utf-8 -*-
from flask import jsonify, request, abort
from . import app
from com.zzh.zzhpay.alipay import alipayInit
from com.zzh.dao_v2.point_logDao import PointLogDao
from com.zzh.dao_v2.orderDaoLYM import OrderDaoV2
from com.zzh.dao_v2.memberDao import MemberDaoYM
import time
from datetime import datetime
import datetime as dt
from com.zzh.dao_v2.couponUsedDao import CouponUsedDao


@app.route('/alipay', methods=['POST'])
def alipay():
    if not request.json:
        abort(400)
    try:
        price = request.json['price']
        order_no = request.json['orderNo']
        subject = request.json['subject']  #主题，可以理解为买的东西的名字
        returnURL = request.json['returnUrl']

    except:
        jsonify({"message": {"code": 0, "status": "缺少必要的参数"}})

    alipay = alipayInit.alipay_init()
    order_string = alipay.api_alipay_trade_wap_pay(
        subject=subject,
        out_trade_no=order_no,
        total_amount=price,
        return_url=returnURL #支付成功后应该跳转的页面

    )

    url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
    return jsonify({"url": url, "message": {"code": 1, "status": "success"}})




@app.route('/checkNotify', methods=["GET","POST"])
def checkNotify():
    localTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    data = request.form.to_dict()
    signature = data.pop('sign')
    # verify
    alipay = alipayInit.alipay_init()
    success = alipay.verify(data, signature)

    print success
    print data

    #print success
    if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
        # print "hello"
        #1.更新订单表的支付状态、交易号、支付时间和实付金额
        paymentStatus = 2
        paymentTime = data["gmt_create"]
        orderNo = data["out_trade_no"]
        payableAmount = data["total_amount"]
        realAmount = data["buyer_pay_amount"]
        pointItemName = data["subject"]
        tradeNo = data["trade_no"]

        orderInfo = OrderDaoV2().selectOrder(orderNo)  # 根据orderNo查询orderType、userId和userName  新增：查询coupon_code，用来更新coupon_used的status状态
        orderType = orderInfo[3]  # 1会员订单 2项目订单
        userId = orderInfo[5]
        userName = orderInfo[6]
        couponCode = orderInfo[29]
        isCoupon = orderInfo[27]

        # print paymentTime
        # print paymentStatus


        #更新order,根据order_no
        alipayOrderInfo = {
            'order_id': orderInfo[0],
            # 1-4
            'order_no': orderNo,  #
            'order_ip': orderInfo[2],  #
            'order_type': orderType,  #
            'trade_no': tradeNo,

            # 5-9
            'user_id': userId,  #
            'user_name': userName,  #
            'payment_id': orderInfo[7],  #
            'payment_fee': str(orderInfo[8]),
            'payment_status': paymentStatus,  # 1未支付，2已支付

            # 10-14
            'payment_time': paymentTime,  #
            'order_created_time': orderInfo[11],  #
            'is_invoice':orderInfo[12],  #
            'invoice_title': orderInfo[13],
            'invoice_taxes': str(orderInfo[14]),

            # 15-19
            'payable_amount': payableAmount,  #
            'real_amount': realAmount,  #
            'order_amount': str(orderInfo[17]),  #
            'order_point': orderInfo[18],
            'is_member': orderInfo[19],

            # 20-24
            'member_name': orderInfo[20],  #
            'member_email': orderInfo[21],  #
            'member_telephone': orderInfo[22],  #
            'member_province': orderInfo[23],
            'member_city': orderInfo[24],

            # 25-29
            'member_district': orderInfo[25],  #
            'member_address': orderInfo[26],  #
            'is_coupon': orderInfo[27],  #
            'coupon_name': orderInfo[28],
            'coupon_code': couponCode,

            # 30-34
            'coupon_type':orderInfo[30],  #
            'coupon_conditions': orderInfo[31],  #
            'coupon_discount': orderInfo[32],  #
            'service_content':orderInfo[33],
            'service_contract': orderInfo[34],

            # 35-39
            'service_code': orderInfo[35],  #
            'service_name': orderInfo[36],  #
            'service_price': str(orderInfo[37]),  #
            'service_rate': str(orderInfo[38]),
            'item_name': orderInfo[39],

            # 40-44
            'item_content': orderInfo[40],  #
            'item_url': orderInfo[41],  #
            'item_address': orderInfo[42],  #
            'item_publishdate': orderInfo[43],
            'item_deadline': orderInfo[44],

            # 45-49
            'item_handlername': orderInfo[45],  #
            'item_handlerphone': orderInfo[46],  #
            'dept_id': orderInfo[47],  #
            'order_status': orderInfo[48],
            'order_product_is_success': orderInfo[49],
            'order_message':orderInfo[50],
            'item_id': orderInfo[51]
            #'coupon_id': request.json.get('couponId'),

        }
        # print alipayOrderInfo["payment_time"]
        # print alipayOrderInfo["payment_status"]
        if isCoupon: #如果使用了优惠券，则根据userId, couponId更新优惠券的状态
            try:
                couponId = couponCode
                rsCouponUsed = CouponUsedDao().updateCouponUsedByCouponIdAndUserid(userId, couponId)

            except Exception, e:
                return jsonify({"message": {"code": 0, "info": e}})
        try:
            rsOrder = OrderDaoV2().updateOrder(alipayOrderInfo)
            # print "rsOrder:"
            # print rsOrder
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": e}})

        #2.新增积分详细记录，point_log表

        point_log_info = {
            "user_id": userId,
            "username": userName,
            "point_item_name": pointItemName, #设置为订单的subject字段
            "point_value": realAmount, #积分数
            "remark": "收入积分",
            "is_income": 1, #是否收入积分,1是收入，2是消费
            "create_time": paymentTime
        }
        try:
            rsPointLog = PointLogDao().add_point_log(point_log_info)
            print "rsPointLog:"
            print rsPointLog
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": e}})

        #处理会员表（member表）,这里有点疑问，暂时先只更新会员积分（member_points）
        try:
            oldInfo = MemberDaoYM().selectMemberByUserId(userId)
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})
        if point_log_info["is_income"] == 1:  # 1是收入，2是消费
            memberPoints = float(realAmount) + float(oldInfo[6])  # 积分就等于realAmount
        if point_log_info["is_income"] == 2:
            memberPoints = float(oldInfo[6]) - float(realAmount)

        # print "abcdefg:"
        # print memberPoints
        # print realAmount
        # print oldInfo[6]
        if orderType == 1: #vip会员订单(开通或续费会员)  ，orderType=2 项目订单
            isVip = 1
            try:
                member_expired = oldInfo[8] #会员期限
                # print member_expired
                # print type(member_expired)
                localTime = time.strftime('%Y-%m-%d', time.localtime(time.time()))
                localTime=datetime.date(datetime.strptime(localTime, "%Y-%m-%d"))
                # print type(localTime)
                #member_expired = time.strftime('%Y-%m-%d', time.localtime(member_expired))
                # print localTime
                # print member_expired
                #
                # print type(orderInfo[51])
                year = int(orderInfo[51]) * 365
                year = dt.timedelta(days=year)
                if member_expired > localTime:
                    member_expired = member_expired + year
                else:
                    member_expired = localTime + year
            # print member_expired
            except Exception, e:
                return "fail"  #member_expired处理问题，直接返回支付失败
        if orderType == 2:
            isVip = oldInfo[25]
            member_expired = oldInfo[8]  # 会员期限


        newMemberInfo = {

            'member_id': oldInfo[0],  #
            'user_id': userId,  #
            'invited_code': oldInfo[2],  #
            'member_code': oldInfo[3],  #
            'member_name': oldInfo[4],

            'member_email': oldInfo[5],  #
            'member_points': memberPoints,  #
            'member_balance': oldInfo[7],  #
            'member_expired': member_expired,
            'industry_id': oldInfo[9],

            'province_id': oldInfo[10],  #
            'city_id': oldInfo[11],  #
            'district_id': oldInfo[12],  #
            'member_favorite_count': oldInfo[13],
            'member_address': oldInfo[14],

            'member_busness': oldInfo[15],  #
            'member_type': oldInfo[16],  #
            'sp_knowledge': oldInfo[17],  #
            'sp_revenue': oldInfo[18],
            'sp_employee': oldInfo[19],

            'sp_industrycode': oldInfo[20],  #
            'tm_industrycode': oldInfo[21],  #
            'tm_deptcode': oldInfo[22],  #
            'tm_level': oldInfo[23],
            'register_code': oldInfo[24],
            'is_vip': isVip  # 默认0不是vip会员（普通用户），1是vip会员
        }

        if not newMemberInfo:
            return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
        try:
            rsMember = MemberDaoYM().updateMemberByUserId(newMemberInfo)
            # print "rsMember:"
            # print rsMember
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})

        if rsOrder and rsPointLog and rsMember:
            return "success"
    else:
        return "fail"




